package com.aeasycredit.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerThree {

	public static void main(String[] args) throws IOException {
		int port = 18080;
		ServerSocket server = new ServerSocket(port);
		System.out.println("server start...");
		
		char theEndOfRecord = (char)19;

		Socket socket = server.accept();
        // 建立好连接后，从socket中获取输入流，并建立缓冲区进行读取
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int len;
        StringBuilder sb = new StringBuilder();
        while ((len = inputStream.read(bytes)) != -1) {
          // 注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
         String str = new String(bytes, 0, len, "UTF-8");
         sb.append(str);
         
         int endIndex = str.indexOf(theEndOfRecord);
         if (endIndex >= 0) {
        	 break;
         }
        }
        System.out.println("get message from client: " + sb);
		
		
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("Hello Client,I get the message.\r\n".getBytes("UTF-8"));
        outputStream.flush();
		
		inputStream.close();
		outputStream.close();
		server.close();
	}

}
